<template>
    <div class="coating">
        <div class="model">
            <span class="iconfont icon-bianzu3" @click="closeCoating"></span>
            <div class="video" :style="{opacity: vList.length > 0 ? 1 : 0.8}">
                <template v-if="vList.length > 0">
                    <template v-for="item in vList">
                        <div :id="'remote_video_panel_' + item" :key="item" class="video-view">
                            <div :id="'remote_video_' + item" class="video-placeholder"></div>
                            <div :id="'remote_video_info_' + item" class="video-profile"></div>
                            <div :id="'video_autoplay_' + item" class="autoplay-fallback"></div>
                        </div>
                    </template>
                </template>
                <template v-else>
                    <div class="vLoading">
                        <div>
                            <img :src="require('@/static/img/bigData/timg.gif')" alt="">
                            <div>等待对方加入中</div>
                        </div>
                    </div>
                </template>
            </div>
            <div class="videoList">
                <div id="local_stream" class="video-view"></div>
            </div>
            <div class="info">
                <div>
                    <span>姓名：{{ bmInfoWindow.name }}</span>
                    <span>单位：{{ bmInfoWindow.workUnits }}</span>
                    <span>执法证号：529900ZF00020017</span>
                </div>
                <div>
                    <span>当前执法案件</span>
                    <span>140901201912190101</span>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import AgoraRTC from 'agora-rtc-sdk'

export default {
    name: 'Coating',
    props: ['bmInfoWindow'],
    data () {
        return {
            rtc: {
                client: null,
                joined: false,
                published: false,
                localStream: null,
                remoteStreams: [],
                params: {}
            },
            option: {
                appID: 'e08a51cf80804d94a4313d51555c7cc5',
                channel: 'yyyadmin',
                uid: null,
                token: '',
                microphoneId: '',
                cameraId: ''
            },
            vList: []
        }
    },
    mounted () {
        this.init()
        this.peerLeave()
        this.streamPublished()
        this.streamAdded()
        this.streamSubscribed()
        this.streamRemoved()
        if (this.rtc.localStream) {
            this.leave()
        }
    },
    methods: {
        // 当对等用户离开通道时发生;例如，对等用户调用Client.leave。
        peerLeave: function () {
            const _this = this
            _this.rtc.client.on('peer-leave', function (evt) {
                const id = evt.uid
                const streams = _this.rtc.remoteStreams.filter(e => id !== e.getId())
                const peerStream = _this.rtc.remoteStreams.find(e => id === e.getId())
                if (peerStream && peerStream.isPlaying()) {
                    peerStream.stop()
                }
                _this.rtc.remoteStreams = streams
                if (id !== _this.rtc.params.uid) {
                    _this.removeView(id)
                    _this.$message({
                        message: '同伴离开' + id,
                        type: 'success'
                    })
                }
            })
        },
        // 在发布本地流时发生。
        streamPublished: function () {
            const _this = this
            this.rtc.client.on('stream-published', function (evt) {
                _this.$message({
                    message: '流出版成功',
                    type: 'success'
                })
            })
        },
        // 在添加远程流时发生。
        streamAdded: function () {
            const _this = this
            _this.rtc.client.on('stream-added', function (evt) {
                const remoteStream = evt.stream
                const id = remoteStream.getId()
                if (id !== _this.rtc.params.uid) {
                    _this.rtc.client.subscribe(remoteStream, function (err) {
                        console.log('stream subscribe failed', err)
                    })
                }
                _this.$message({
                    message: '流添加了远程uid: ' + id,
                    type: 'success'
                })
            })
        },
        // 当用户订阅远程流时发生。
        streamSubscribed: function () {
            const _this = this
            _this.rtc.client.on('stream-subscribed', function (evt) {
                const remoteStream = evt.stream
                const id = remoteStream.getId()
                _this.addView(id)
                _this.$nextTick(() => {
                    _this.rtc.remoteStreams.push(remoteStream)
                    remoteStream.play('remote_video_' + id)
                })
                _this.$message({
                    message: '流订阅远程uid: ' + id,
                    type: 'success'
                })
            })
        },
        // 在远程流被移除时发生;例如，对等用户调用Client.unpublish。
        streamRemoved: function () {
            const _this = this
            _this.rtc.client.on('stream-removed', function (evt) {
                const remoteStream = evt.stream
                const id = remoteStream.getId()
                if (remoteStream.isPlaying()) {
                    remoteStream.stop()
                }
                _this.rtc.remoteStreams = _this.rtc.remoteStreams.filter(function (stream) {
                    return stream.getId() !== id
                })
                // Stop playing the remote stream.
                // remoteStream.stop('remote_video_' + id)
                // Remove the view of the remote stream.
                _this.removeView(id)
                _this.$message({
                    message: '流删除远程uid: ' + id,
                    type: 'success'
                })
            })
        },
        init: function () {
            const _this = this
            this.rtc.client = AgoraRTC.createClient({
                mode: 'rtc',
                codec: 'h264'
            })
            this.rtc.client.init(this.option.appID, function () {
                _this.$message({
                    message: 'RTC初始化成功！',
                    type: 'success'
                })
                _this.join()
            }, (err) => {
                console.error(err)
            })
        },
        join: function () {
            const _this = this
            if (_this.rtc.joined) {
                _this.$message({
                    message: '你已经加入了！',
                    type: 'success'
                })
                return false
            }
            _this.rtc.client.join(_this.option.token ? _this.option.token : null, _this.option.channel, _this.option.uid ? +_this.option.uid : null, function (uid) {
                _this.$message({
                    message: '加入频道: ' + _this.option.channel + ' 成功！, uid: ' + uid,
                    type: 'success'
                })
                _this.rtc.joined = true
                _this.rtc.params.uid = uid
                _this.localStreamInit()
            }, function (err) {
                console.error('client join failed', err)
            })
        },
        localStreamInit: function () {
            const _this = this
            // 创建本地流
            _this.rtc.localStream = AgoraRTC.createStream({
                streamID: _this.rtc.params.uid,
                audio: true,
                video: true,
                screen: false
            })
            // 初始化本地流。初始化完成后执行的回调函数
            _this.rtc.localStream.init(function () {
                _this.$message({
                    message: '初始化流成功！',
                    type: 'success'
                })
                // play stream with html element id "local_stream"
                _this.rtc.localStream.play('local_stream')
                _this.publish()
            }, function (err) {
                console.error('初始化失败：', err)
            })
        },
        publish: function () {
            const _this = this
            if (!_this.rtc.client) {
                _this.$message({
                    message: '请先入座！',
                    type: 'warning'
                })
                return false
            }
            if (_this.rtc.published) {
                _this.$message({
                    message: '你已经发表！',
                    type: 'warning'
                })
                return false
            }

            const oldState = _this.rtc.published
            _this.rtc.client.publish(_this.rtc.localStream, function (err) {
                _this.rtc.published = oldState
                _this.$message({
                    message: '发布失败！',
                    type: 'warning'
                })
                console.error(err)
            })
            _this.rtc.published = true
        },
        unpublish: function () {
            const _this = this
            if (!_this.rtc.client) {
                _this.$message({
                    message: '请先入座！',
                    type: 'warning'
                })
                return false
            }
            if (_this.rtc.published) {
                _this.$message({
                    message: '你已经发表！',
                    type: 'warning'
                })
                return false
            }
            const oldState = _this.rtc.published
            _this.rtc.client.unpublish(_this.rtc.localStream, function (err) {
                _this.rtc.published = oldState
                _this.$message({
                    message: '取消发布失败！',
                    type: 'warning'
                })
                console.error(err)
            })
            _this.rtc.published = false
        },
        leave: function () {
            const _this = this
            if (!_this.rtc.client) {
                _this.$message({
                    message: '请先加入!',
                    type: 'warning'
                })
                return false
            }
            if (!_this.rtc.joined) {
                _this.$message({
                    message: '你不在频道!',
                    type: 'warning'
                })
                return false
            }
            _this.rtc.client.leave(function () {
                // Stop playing the local stream
                // stop stream
                if (_this.rtc.localStream.isPlaying()) {
                    _this.rtc.localStream.stop()
                }
                // Close the local stream
                _this.rtc.localStream.close()
                // Stop playing the remote streams and remove the views
                for (let i = 0; i < _this.rtc.remoteStreams.length; i++) {
                    const stream = _this.rtc.remoteStreams.shift()
                    const id = stream.getId()
                    if (stream.isPlaying()) {
                        stream.stop()
                        _this.removeView(id)
                    }
                }
                _this.rtc.localStream = null
                _this.rtc.remoteStreams = []
                _this.rtc.client = null
                _this.rtc.published = false
                _this.rtc.joined = false
                _this.$message({
                    message: '客户端离开通道成功',
                    type: 'success'
                })
            }, function (err) {
                console.log('channel leave failed')
                console.error(err)
            })
        },
        addView: function (id) {
            this.vList.push(id)
        },
        removeView: function (id) {
            console.log('===========')
            console.log(this.vList.indexOf(id))
            if (this.vList.indexOf(id) > -1) {
                this.vList.splice(this.vList.indexOf(id), 1)
            }
        },
        closeCoating: function () {
            this.leave()
            this.$emit('close')
        }
    },
    beforeDestroy () {
        if (this.rtc.localStream) {
            this.leave()
        }
    }
}
</script>

<style scoped lang="less">
.coating {
    position: fixed;
    width: 100vw;
    height: 100vh;
    background: rgba(0, 0, 0, 0.8);
    z-index: 998;
    align-items: center;
    display: flex;
    justify-content: center;

    .model {
        width: 30vw;
        min-width: 500px;
        height: 90vh;
        position: relative;

        .video {
            background: #FFFFFF;
            position: absolute;
            width: 100%;
            height: 100%;
            .video-view {
                height: 100%; position: relative;
                .video-placeholder {
                    height: 100%; width: 100%; position: absolute;
                }
            }

            .vLoading {
                width: 100%; height: 100%; position: absolute;
                display: flex; align-items: center; z-index: 2;
                img {
                    width: 50%;
                }
                div {
                    width: 100%; transform: translateY(-50%); text-align: center;
                    font-size: 2rem; color: rgba(0,0,0,0.8);
                }
            }

            video {
                width: 100%;
                height: 100%;
                position: absolute;
            }
        }
        .iconfont {
            font-size: 5rem;
            color: red;
            position: absolute;
            bottom: 6rem;
            left: 50%;
            transform: translateX(-50%);
            cursor: pointer;
            z-index: 9;
        }
        .videoList {
            position: absolute; width: 120px; right: -130px; height: 100%; overflow: auto;
            .video-view {
                height: 180px; position: relative; border-radius: 10px; overflow: hidden; border: .2rem #00B1FF solid; margin-bottom: 1rem;
                .video-placeholder {
                    height: 100%; width: 100%; position: absolute;
                }
            }
        }
        .info {
            position: absolute;
            background: rgba(0, 0, 0, 0.6);
            color: #FFFFFF;
            font-size: 1.4rem;
            display: flex;
            width: 100%;
            justify-content: space-between;
            box-sizing: border-box;
            line-height: 3.2rem;
            padding: 0 0 12rem 0;
            bottom: 0;

            div {
                flex: 1;
                padding: 2rem;

                span {
                    display: block;
                    line-height: 3.2rem;
                    font-size: 1.4rem;
                }

                &:nth-child(1) {
                    border-right: 0.1rem rgba(255, 255, 255, 0) solid;
                }
            }
        }
    }
}

</style>
